package com.supor.md_video.model;

import android.app.Application;
import android.text.TextUtils;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseLocalConfigBean;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.base.SingleLiveEvent;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.md_video.api.VideoApiImpl;
import com.supor.md_video.entity.FavoritStateBean;
import com.supor.md_video.entity.VideoCommListBean;
import com.supor.md_video.entity.VideoCommListResultBean;
import com.supor.md_video.entity.VideoCommThumbsBean;
import com.supor.md_video.entity.VideoFavoritBean;
import com.supor.md_video.entity.VideoListBean;

import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import autodispose2.AutoDisposeConverter;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class VideoListModel extends BaseViewModel {
    public static final int PAGE_SIZE = 20;

    private Disposable loadVideoListDataDisposable;
    private SingleLiveEvent<Result<VideoCommListBean>> videoCommAddResult = new SingleLiveEvent<>();
    private SingleLiveEvent<Result<VideoCommListResultBean>> videoCommListResult = new SingleLiveEvent<>();
    private MutableLiveData<BaseLocalConfigBean> commThumbsResult = new MutableLiveData<>();

    private MutableLiveData<Result<VideoListBean>> videoListResult = new MutableLiveData<>();

    private MutableLiveData<FavoritStateBean> favoritResult = new MutableLiveData<>();

    private MutableLiveData<Result> shareUpdateResult = new MutableLiveData<>();

    public VideoListModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Result<VideoListBean>> getVideoListResult() {
        return videoListResult;
    }

    public void loadVideoListData(int page,
                                  AutoDisposeConverter<BaseApiResult<VideoListBean>> autoDisposeConverter) {
        if (null != loadVideoListDataDisposable && !loadVideoListDataDisposable.isDisposed()) {
            loadVideoListDataDisposable.dispose();
        }
        VideoApiImpl.getInstance().getVideoList("RELEASE", "VIDEO", "0",
                20, page)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        loadVideoListDataDisposable = disposable;
                    }
                })
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoListBean>>() {
                    @Override
                    public void accept(BaseApiResult<VideoListBean> apiResult) throws Exception {
                        videoListResult.setValue(new Result.Success<>(apiResult.data));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Logc.e("accept: " + throwable);
                        videoListResult.setValue(new Result.Error(new Exception(throwable)));
                    }
                });
    }

    public boolean inRequest() {
        return null != loadVideoListDataDisposable && !loadVideoListDataDisposable.isDisposed();
    }

    public void subRecipe(String addrId,
                          String bossUserId,
                          int position,
                          AutoDisposeConverter<BaseApiResult<VideoFavoritBean>> autoDisposeConverter) {
        VideoApiImpl.getInstance().subRecipe(addrId, bossUserId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoFavoritBean>>() {
                    @Override
                    public void accept(BaseApiResult<VideoFavoritBean> stringBaseApiResult) throws Exception {
                        FavoritStateBean favoritStateBean = new FavoritStateBean();
                        favoritStateBean.setId(addrId);
                        favoritStateBean.setLocalCountType(1);
                        favoritStateBean.setLocalPosition(position);
                        favoritResult.setValue(favoritStateBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        favoritResult.setValue(new Result.Error(new Exception(throwable)));
                    }
                });

    }

    public void unSubRecipe(String addrId,
                            int position,
                            AutoDisposeConverter<BaseApiResult<VideoFavoritBean>> autoDisposeConverter) {
        VideoApiImpl.getInstance().subRecipeDel(addrId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoFavoritBean>>() {
                    @Override
                    public void accept(BaseApiResult<VideoFavoritBean> videoFavoritBeanBaseApiResult) throws Exception {
                        FavoritStateBean favoritStateBean = new FavoritStateBean();
                        favoritStateBean.setId(addrId);
                        favoritStateBean.setLocalCountType(-1);
                        favoritStateBean.setLocalPosition(position);
                        favoritResult.setValue(favoritStateBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        favoritResult.setValue(new Result.Error(new Exception(throwable)));
                    }
                })
        ;
    }

    public MutableLiveData<FavoritStateBean> getFavoritResult() {
        return favoritResult;
    }

    public void loadVideoCommData(String addrId,
                                  int page,
                                  AutoDisposeConverter<BaseApiResult<VideoCommListResultBean>> autoDisposeConverter
    ) {
        VideoApiImpl.getInstance().getVideoCommList(addrId,
                PAGE_SIZE,
                page, "RECIPE_ID")
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoCommListResultBean>>() {
                    @Override
                    public void accept(BaseApiResult<VideoCommListResultBean> videoCommListBeanBaseApiResult) throws Exception {
                        videoCommListResult.setValue(new Result.Success<>(videoCommListBeanBaseApiResult.data));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Logc.e("accept: " + throwable);
                        videoCommListResult.setValue(new Result.Error(new Exception(throwable)));
                    }
                });
    }

    public MutableLiveData<Result<VideoCommListResultBean>> getVideoCommListResult() {
        return videoCommListResult;
    }

    public void sendComm(String text, String addrId, String recipeId, int position,
                         AutoDisposeConverter<BaseApiResult<VideoCommListBean>> autoDisposeConverter) {
        if (null == GlobalDataCache.userInfo || !AppAgent.isLogin()) {
            ToastUtils.getInstance().showToast(getApplication(), "请先登录");
            return;
        }
        VideoApiImpl.getInstance().commFilter(text)
                .filter(result -> result.isSuccess())
                .flatMap((Function<BaseApiResult<String>, ObservableSource<BaseApiResult<VideoCommListBean>>>) result -> {
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String currentTime = sdf.format(date);
                    return VideoApiImpl.getInstance().addComm(text,
                            GlobalDataCache.userInfo.getBossUserId(),
                            addrId, recipeId, text, currentTime
                    ).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoCommListBean>>() {
                               @Override
                               public void accept(BaseApiResult<VideoCommListBean> videoCommListBeanBaseApiResult) throws Exception {
                                   videoCommListBeanBaseApiResult.data.setIsMyself(1);
                                   videoCommListBeanBaseApiResult.data.setHeadPortaint(GlobalDataCache.userInfo.getFaceImage());
                                   videoCommListBeanBaseApiResult.data.setNickName(GlobalDataCache.userInfo.getNickName());
                                   videoCommListBeanBaseApiResult.data.setLocalId(addrId);
                                   videoCommListBeanBaseApiResult.data.setLocalPosition(position);
                                   videoCommAddResult.setValue(new Result.Success<>(videoCommListBeanBaseApiResult.data));
                               }
                           },
                        throwable -> videoCommAddResult.setValue(new Result.Error(new Exception(throwable))));

    }

    public MutableLiveData<Result<VideoCommListBean>> getVideoCommAddResult() {
        return videoCommAddResult;
    }

    public void commThumbs(String replyId, int position,
                           AutoDisposeConverter<BaseApiResult<VideoCommThumbsBean>> autoDisposeConverter) {
        if (null == GlobalDataCache.userInfo || !AppAgent.isLogin()) {
//            ToastUtils.getInstance().showToast(getApplication(), "请先登录");
            AppAgent.showLogin(false);
            return;
        }
        VideoApiImpl.getInstance().commThumbs(replyId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoCommThumbsBean>>() {
                    @Override
                    public void accept(BaseApiResult<VideoCommThumbsBean> stringBaseApiResult) throws Exception {
                        BaseLocalConfigBean baseLocalConfigBean = new BaseLocalConfigBean();
                        baseLocalConfigBean.setLocalId(replyId);
                        baseLocalConfigBean.setLocalType(1);
                        baseLocalConfigBean.setLocalPosition(position);
                        baseLocalConfigBean.setLocalLikeId(stringBaseApiResult.data.getLikeId());
                        commThumbsResult.setValue(baseLocalConfigBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    public void commThumbsDel(String replyId, String likeId, int position,
                              AutoDisposeConverter<BaseApiResult<String>> autoDisposeConverter) {
        if (null == GlobalDataCache.userInfo || !AppAgent.isLogin()) {
//            ToastUtils.getInstance().showToast(getApplication(), "请先登录");
            AppAgent.showLogin(false);
            return;
        }
        if (TextUtils.isEmpty(likeId)) {
            return;
        }
        VideoApiImpl.getInstance().commThumbsDel(likeId)
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<String>>() {
                    @Override
                    public void accept(BaseApiResult<String> stringBaseApiResult) throws Exception {
                        BaseLocalConfigBean baseLocalConfigBean = new BaseLocalConfigBean();
                        baseLocalConfigBean.setLocalId(replyId);
                        baseLocalConfigBean.setLocalType(-1);
                        baseLocalConfigBean.setLocalPosition(position);
                        commThumbsResult.setValue(baseLocalConfigBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    public MutableLiveData<BaseLocalConfigBean> getCommThumbsResult() {
        return commThumbsResult;
    }

    public MutableLiveData<Result> getShareUpdateResult() {
        return shareUpdateResult;
    }

    public void shareUpdate(String recipeId) {
        VideoApiImpl.getInstance().shareUpdate(recipeId)
                .subscribe(stringBaseApiResult -> {
                    shareUpdateResult.setValue(new Result.Success(Constants.Value.SUCCESS));
                }, throwable -> shareUpdateResult.setValue(new Result.Error(new Exception(throwable))));
    }
}